import { RequestOptions, RequestResult } from "./base/interface";
import { ClientOptions, createBaseApi } from "./flora-api-base";
import { createDashApi } from "./flora-api-dash";
import { createUsersApi } from "./flora-api-users";
import { createDzqApi } from "./flora-api-dzq";
import { createTr } from "./flora-tr";

export interface FloraClient {
  request: <T>(opts: RequestOptions) => Promise<RequestResult<T>>;
  setLoginToken: (token: string) => Promise<void>;
  loginToken: string;
  getLoginToken: () => string
  users: ReturnType<typeof createUsersApi>,
  dzq: ReturnType<typeof createDzqApi>,
  dash: ReturnType<typeof createDashApi>,
  tr: ReturnType<typeof createTr>,
  lang: "cn" | "en",
  setLang: (lang: "cn" | "en") => Promise<void>,
}

function runInNextEventLoop<T extends ((() => void) | undefined)>(f: T): T {
  if (!f) {
    return undefined as any as T;
  }
  return function () {
    setTimeout(f, 0);
  } as any as T;
}




export function NewFloraClient(options: ClientOptions): FloraClient {
  options = {
    ...options,
    onLoginStatusChanged: runInNextEventLoop(options.onLoginStatusChanged),
  }

  const base = createBaseApi(options);
  const users = createUsersApi({
    clientOptions: options,
    base,
  });
  const dzq = createDzqApi({
    clientOptions: options,
    base,
  });
  const dash = createDashApi({
    clientOptions: options,
    base,
  })

  const tr = createTr({
    clientOptions: options,
    base,
  })

  return {
    request: base.request,
    setLoginToken: base.setLoginToken,
    loginToken: base.loginToken,
    getLoginToken: base.getLoginToken,
    lang: base.lang,
    setLang: base.setLang,
    users,
    dzq,
    dash,
    tr,
  };
}
